package com.glsc.ngateway.flowable.listener.demandmanagement;

import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.dto.AppendIdDto;
import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableAssigneeDto;
import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableDemandDto;
import com.glsc.ngateway.flowable.constant.FlowableConstant;
import com.glsc.ngateway.flowable.service.FlowableAssigneeService;
import com.glsc.ngateway.flowable.service.FlowableDemandService;
import com.glsc.ngateway.flowable.service.FlowableEhrEmpService;
import com.glsc.ngateway.flowable.service.feignservice.OaflowFeignService;
import com.glsc.ngateway.flowable.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class DemandManagementOaHandler implements TaskListener, ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(DemandManagementOaHandler.class);

    @Autowired
    private RuntimeService runtimeService;

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }


    @Override
    public void notify(DelegateTask delegateTask) {

        try {
            String processId = delegateTask.getProcessInstanceId();
            if (delegateTask.getVariable("oaGroup") == null) {
                throw new Exception("发起oa会签，oaGroup为空！");
            }
            Set<String> oaGroup = (Set<String>) delegateTask.getVariable("oaGroup");
            logger.info("---------------------oaGroup=" + oaGroup);
            if (oaGroup == null) {
                throw new Exception("发起oa会签1，oaGroup为空！");
            }
            String createUser = "mw";
            FlowableAssigneeService flowableAssigneeService = (FlowableAssigneeService) applicationContext.getBean("flowableAssigneeService");
            List<FlowableAssigneeDto> list = flowableAssigneeService.findAssigneeByKey("DemandManagement", delegateTask.getTenantId());
            for (FlowableAssigneeDto l : list) {
                if ("advanceTask".equals(l.getTaskDefinitionKey())) {
                    createUser = l.getAssigneeName();
                    break;
                }
            }
            FlowableDemandService flowableDemandService = (FlowableDemandService) applicationContext.getBean("flowableDemandService");
            List<FlowableDemandDto> exist = flowableDemandService.findByProcessInstanceId(processId);
            FlowableDemandDto demandExist = exist.get(0);
            if (demandExist != null) {
                Map<String, Object> oaparam = new HashMap<>();
                oaparam.put("creater", createUser);
                oaparam.put("applicant", createUser);
                String system = FlowableConstant.systemToChineseMap.get(demandExist.getSystemId());
                if (system == null) {
                    system = demandExist.getSystemId();
                }
                oaparam.put("title", "需求确认流程-" + system + "-" + DateUtil.getCurrentDate("yyyy-MM-dd"));
                oaparam.put("applyDate", DateUtil.getCurrentDate("yyyy-MM-dd"));
                oaparam.put("confirmStaff", String.join(",", oaGroup));      //demandExist.getStaff()
//                String content = createDemandContent(objectToMap(demandExist));
//                oaparam.put("content", content);

                oaparam.put("system", system);
                if (StringUtils.isNotEmpty(demandExist.getOriginalStaff())) {
                    oaparam.put("originStaff", demandExist.getOriginalStaff());
                }
                FlowableEhrEmpService flowableEhrEmpService = (FlowableEhrEmpService) applicationContext.getBean("flowableEhrEmpService");
                oaparam.put("staff", demandExist.getStaff());
                if (flowableEhrEmpService != null) {
                    oaparam.put("staff", flowableEhrEmpService.getChineseName(demandExist.getStaff()));
                }
                if (StringUtils.isNotEmpty(demandExist.getDemandDetail())) {
                    oaparam.put("demandDetail", demandExist.getDemandDetail());
                }
                if (StringUtils.isNotEmpty(demandExist.getDemandType())) {
                    oaparam.put("demandType", FlowableConstant.typeToChineseMap.get(demandExist.getDemandType()));
                }
                oaparam.put("createTime", demandExist.getCreateTime());
                if (StringUtils.isNotEmpty(demandExist.getDemandUrl())) {
                    oaparam.put("demandUrl", demandExist.getDemandUrl());
                }
                oaparam.put("demandDepart", demandExist.getDepartment());
                if (StringUtils.isNotEmpty(demandExist.getSolutionGeneral())) {
                    oaparam.put("solutionGeneral", demandExist.getSolutionGeneral());
                }
                if (StringUtils.isNotEmpty(demandExist.getDemandLevel())) {
                    oaparam.put("demandLevel", FlowableConstant.levelToChineseMap.get(demandExist.getDemandLevel()));
                }
//
//[{
//                    "annexId" :"8c0e9e54-6161-4d4c-b76e-3c3981040fef",
//                            "annexName" :"ty.xlsx"
//                },{
//                    "annexId" :"96d763ba-2dde-4630-897f-c3e60b148edf",
//                            "annexName" :"xxx.xlsx"
//                } ]
//
//                "appendix":{
//                    "annexId":
//                    "http://127.0.0.1:10003/oaDownloadAppendix/55f65f04-1feb-43b3-a277-30b718b512ae,http://127.0.0.1:10003/oaDownloadAppendix/1a1d6b36-dbf6-4aae-890c-e6f72f5d49b2",
//                            "annexName":"1.txt,2.txt"
//                },

                if (!StringUtils.isEmpty(demandExist.getSolutionDocument()) || !StringUtils.isEmpty(demandExist.getDemandDocument())) {
                    AppendIdDto appendix = createAppendix(demandExist.getSolutionDocument(), demandExist.getDemandDocument(), applicationContext.getBean(FlowableConstant.class).DOC_WEB_URL_OA);
                    oaparam.put("appendix", appendix);
                }
                OaflowFeignService oaflowFeignService = (OaflowFeignService) applicationContext.getBean("oaflowFeignService");
                String workFlowId = applicationContext.getBean(FlowableConstant.class).WORK_FLOW_ID;
                logger.info("创建流程workflowid:" + workFlowId);
                logger.info("创建流程参数:" + oaparam.toString());
                String result = oaflowFeignService.createOaflow(oaparam, workFlowId);

                JSONObject js = JSONObject.parseObject(result);
                String oacode = js.getString("code");
                if ("0".equals(oacode)) {
                    logger.info("需求管理，在oa创建流程成功！ msg=" + result);
                    String requestid = js.getJSONObject("data").getString("requestid");
                    demandExist.setRequestId(requestid);
                    flowableDemandService.saveDemandSubmit(demandExist);
                } else {
                    logger.error("需求管理，在oa创建流程失败！ msg=" + result);
                    throw new Exception("需求管理，在oa创建流程失败！");
                }
            }
        } catch (Exception e) {
            logger.error("DemandManagementOaHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
            throw new RuntimeException("DemandManagementOaHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
        }
    }

    private AppendIdDto createAppendix(String solutionDoc, String demandDoc, String docurl) {
        List<AppendIdDto> list = JSONObject.parseArray(solutionDoc, AppendIdDto.class);
        AppendIdDto newdto = new AppendIdDto();
        StringBuffer idbuffer = new StringBuffer();
        StringBuffer namebuffer = new StringBuffer();
        if (list != null) {
            for (AppendIdDto d : list) {
                idbuffer.append(docurl + d.getAnnexId()).append(",");
                namebuffer.append(d.getAnnexName()).append(",");
            }
        }
        List<AppendIdDto> list1 = JSONObject.parseArray(demandDoc, AppendIdDto.class);
        if (list1 != null) {
            for (AppendIdDto d : list1) {
                idbuffer.append(docurl + d.getAnnexId()).append(",");
                namebuffer.append(d.getAnnexName()).append(",");
            }
        }

        newdto.setAnnexId(idbuffer.substring(0, idbuffer.length() - 1));
        newdto.setAnnexName(namebuffer.substring(0, namebuffer.length() - 1));
        return newdto;
    }

    private String createDemandContent(Map<String, Object> rMap) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : rMap.entrySet()) {
            String keyhead = FlowableConstant.keyToElementMap.get(entry.getKey());
            if (!StringUtils.isEmpty(keyhead)) {
                String oneElementNode = keyhead + "=" + entry.getValue();
                sb.append(oneElementNode).append("<br/>");
            }
        }
        return sb.toString();
    }

    private Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

}